﻿using App.Dal;
using App.Model;
using App.Untiys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace App.Dal
{
    public class ConfigServices
    {
        static SqlSugarScope dbHelper = SqliteSugarHelper.Db;

        /// <summary>
        /// 删除表
        /// </summary>
        /// <param name="tableName"></param>
        public static void DropTable(string tableName)
        {
            if (dbHelper.DbMaintenance.IsAnyTable(tableName))
                dbHelper.DbMaintenance.DropTable(tableName);
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static void InitializationDataBase()
        {
            //Type types = Assembly
            //    .LoadFrom("App.Model.dll")//如果 .dll报错，可以换成 xxx.exe 有些生成的是exe 
            //    .GetTypes().Where(it => it.FullName.Contains("SysMenu"))//命名空间过滤，可以写其他条件
            //    .First();//断点调试一下是不是需要的Type，不是需要的在进行过滤

            Type[] types = Assembly.LoadFrom("App.Model.dll").GetTypes();
            types.ToList().ForEach(res =>
            {
                var tableName = res.FullName.Replace("App.Model.", "");
                if (tableName.Contains("Sys") || tableName.Contains("Pro"))
                {
                    DropTable(tableName);
                    dbHelper.CodeFirst.InitTables(res);
                }
            });

            Thread.Sleep(200);
            //添加管理员
            dbHelper.Insertable<SysUser>(new SysUser
            {
                Acct = "admin",
                ChName = "系统管理员",
                Disable = 0,
                AddTime = DateTime.Now,
                IsAdmin = 1,
                Pwd = DesEncrypt.Encrypt("1"),
                AddUser = 1,
                DepartId = 1,
                IsDelete = 0,
                RoleId = 0,
                Phone = "13888888888",
                Abandon = 1
            }).InsertColumns(m => new { m.Acct, m.RoleId, m.ChName, m.IsAdmin, m.Abandon, m.Phone, m.Pwd, m.DepartId, m.IsDelete, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();

            #region 系统管理

            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "",
                Disable = 0,
                IconIndex = 361498,
                Name = "系统管理",
                Parent = 0,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            var parent = dbHelper.Queryable<SysMenu>().Where(m => m.Name == "系统管理").First();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Sys.User.FrmList",
                Disable = 0,
                IconIndex = 361447,
                Name = "用户管理",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Sys.Role.FrmList",
                Disable = 0,
                IconIndex = 361445,
                Name = "角色管理",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Sys.Depart.FrmList",
                Disable = 0,
                IconIndex = 361596,
                Name = "部门管理",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Sys.Setting.FrmPwd",
                Disable = 0,
                IconIndex = 361596,
                Name = "修改密码",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Sys.Setting.FrmLog",
                Disable = 0,
                IconIndex = 361597,
                Name = "日志查询",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();

            //dbHelper.Insertable<SysMenu>(new SysMenu
            //{
            //    AddTime = DateTime.Now,
            //    AssemblyPath = "App.Desk.Sys.PLCSetting.FrmList",
            //    Disable = 0,
            //    IconIndex = 361597,
            //    Name = "采样设置",
            //    Parent = parent.Id,
            //    AddUser = 1
            //}).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();

            #endregion

            #region 采样管理

            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "",
                Disable = 0,
                IconIndex = 361498,
                Name = "采样管理",
                Parent = 0,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            parent = dbHelper.Queryable<SysMenu>().Where(m => m.Name == "采样管理").First();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Pro.SamplingData.FrmPlansList",
                Disable = 0,
                IconIndex = 61632,
                Name = "采样记录",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();
            dbHelper.Insertable<SysMenu>(new SysMenu
            {
                AddTime = DateTime.Now,
                AssemblyPath = "App.Desk.Sys.Pails.FrmList",
                Disable = 0,
                IconIndex = 362572,
                Name = "样桶管理",
                Parent = parent.Id,
                AddUser = 1
            }).InsertColumns(m => new { m.AssemblyPath, m.IconIndex, m.Name, m.Parent, m.Disable, m.AddTime, m.AddUser }).ExecuteCommand();

            #endregion

            #region 样桶管理
            for (int i = 1; i <= 6; i++)
            {
                dbHelper.Insertable<SysPail>(new SysPail
                {
                    Current_Value = 0,
                    Current_Weight = 0,
                    PailId = i,
                    PailName = $"{i}#桶",
                    Threshold_Value = 20,
                    Threshold_Weihght = 15,
                    Disable = 0,
                    BatchCode = "",
                }).InsertColumns(m => new { m.Current_Value, m.Current_Weight,m.BatchCode, m.PailId, m.PailName, m.Threshold_Value, m.Threshold_Weihght, m.Disable }).ExecuteCommand();
            }
            #endregion

            dbHelper.Insertable<ProDepart>(new ProDepart
            {
                AddTime = DateTime.Now,
                IsDelete = 0,
                DepartName = "采样班",
                Remarks = "",
                AddUser = 1,
                Disable = 0,
            }).InsertColumns(m => new { m.DepartName, m.Remarks, m.IsDelete, m.AddTime, m.AddUser, m.Disable }).ExecuteCommand();

        }

        /// <summary>
        /// 获取全部启用的菜单
        /// </summary>
        /// <returns></returns>
        public static List<SysMenu> GetNoDisableMenus()
        {
            return dbHelper.Queryable<SysMenu>().Where(m => m.Disable == 0).ToList();
        }

        /// <summary>
        /// 插入PLC错误警告信息   15分钟内只会写入一条相同的记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool AddErrors(ProErrors model)
        {
            try
            {
                bool result = false;
                if (dbHelper.Queryable<ProErrors>().Where(m => m.Errors == model.Errors && m.AddTime > DateTime.Now.AddMinutes(-1)).Count() <= 0)
                    result = dbHelper.Insertable<ProErrors>(new ProErrors
                    {
                        AddTime = DateTime.Now,
                        GroupName = model.GroupName,
                        Errors = model.Errors,
                        PLCAddr = model.PLCAddr
                    }).InsertColumns(m => new { m.GroupName, m.Errors, m.AddTime, m.PLCAddr }).ExecuteCommand() > 0;
                return result;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 清空报警信息
        /// </summary>
        /// <param name="delEndTime">删除此时间之前的数据</param>
        /// <returns></returns>
        public static bool ClearErrors(DateTime delEndTime)
        {
            return dbHelper.Deleteable<ProErrors>().Where(m => m.AddTime < delEndTime).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 获取全部启用的菜单
        /// </summary>
        /// <returns></returns>
        public static List<SysMenu> GetNoDisableNoAdminMenus(List<string> authoritys)
        {
            var parentIds = dbHelper.Queryable<SysMenu>()
                .Where(m => authoritys.Contains(m.Name))
                .Where(m => m.Disable == 0).Select(m => m.Parent).ToList();
            return dbHelper.Queryable<SysMenu>()
                .Where(m => authoritys.Contains(m.Name) || parentIds.Contains(m.Id))
                .Where(m => m.Disable == 0).ToList();
        }

    }
}
